<html>
<head>

<title>Groovy Goodness: Collate a List into Sub-lists</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Collate a List into Sub-lists</h3>

<div class="post">
<p>I totally missed the new <code>collate()</code> method for <code>List</code> objects available since Groovy 1.8.6. With this method we can divide a list into sub-lists of a specified size. We can include a boolean parameter to indicate if we want to include remainders that don't fit in the specified size of the collated sub-lists. Finally we can use a parameter to define how many steps we go through the list before dividing the list into sub-lists.</p><pre class="brush:groovy">def letters = 'a'..'g'

assert letters.collate(3) == [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

// Step through original list with 
// 2 steps and collate.
assert letters.collate(3, 2) == [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g']]

// Don't include remainder in result.
// Default a remainder is included in the result.
boolean remainder = false
assert letters.collate(3, remainder) == [['a', 'b', 'c'], ['d', 'e', 'f']]
assert letters.collate(3, 2, remainder) == [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g']]
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>